<?php

namespace app\common\model;

use think\Model;

class ShopProduct extends Model
{
    // 表名
    protected $name = 'shop_product';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'is_top_text',
        'status_text'
    ];

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    public function getIsTopList()
    {
        return ['0' => __('Is_top 0'),'1' => __('Is_top 1')];
    }     

    public function getStatusList()
    {
        return ['normal' => __('Normal'),'hidden' => __('Hidden')];
    }

    public static function getList()
    {
        return self::column('cat_name');
    }

    public function getIsTopTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['is_top'];
        $list = $this->getIsTopList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function setSpecNameAttr($value)
    {
        return str_replace("\r\n", ",", $value);
    }

    public function getSpecNameAttr($value)
    {
        return str_replace(',', "\r\n", $value);
    }

    public function setSpecPriceAttr($value)
    {
        return str_replace("\r\n", ",", $value);
    }

    public function getSpecPriceAttr($value)
    {
        return str_replace(',', "\r\n", $value);
    }

    public function setProAttrAttr($value)
    {
        return json_encode(array_combine($value['field'], $value['value']), JSON_UNESCAPED_UNICODE);
    }

    public function getProAttrAttr($value)
    {
        return json_decode($value,true);
    }
}
